package info.javatech.jmf.client.wrappers;

import info.javatech.jmf.client.controller.JMFAbstractComponentWrapper;
import info.javatech.jmf.client.controller.exceptions.ComponentConstructionException;
import info.javatech.jmf.client.controller.wsclient.PCommand;
import info.javatech.jmf.client.controller.wsclient.PComponent;
import info.javatech.jmf.client.controller.wsclient.PEvent;
import info.javatech.jmf.client.util.InvalidComponentException;
import info.javatech.jmf.client.util.PComponentUtils;
import info.javatech.jmf.common.ProtocolConstants;
import info.javatech.jmf.common.components.CommandConstants;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Item;

public class CommandWrapper extends JMFAbstractComponentWrapper{
    
    private String commandId;
    
    public Object constructInstanceImplementation(PComponent pc) throws ComponentConstructionException {
        Command command;
        try {
            
            String shortName = PComponentUtils.getStringProperty(pc, CommandConstants.SHORT_TITLE_PROPERTY_NAME);
            String longName = PComponentUtils.getStringProperty(pc, CommandConstants.LONG_TITLE_PROPERTY_NAME);
            int type = PComponentUtils.getIntProperty(pc, CommandConstants.TYPE_PROPERTY_NAME);
            int priority = PComponentUtils.getIntProperty(pc, CommandConstants.PRIORITY_PROPERTY_NAME);
            
            command = new Command(
                    shortName,
                    longName,
                    type,
                    priority);
            
            return command;
        } catch (InvalidComponentException ex) {
            throw new ComponentConstructionException();
        }
        
    }
    
    public PComponent persistImplementation(Object obj, PComponent eventSource) {
        Command command = (Command) obj;
        
        PComponent res = new PCommand();
        res.setType(CommandConstants.TYPE_NAME);
        
        if (eventSource!=null&&eventSource.getId()!=null&&eventSource.getId().equals(this.getStoredComponentId(obj))) {
            res.setPropertyNames(new String[]{CommandConstants.ACTION_PROPERTY_NAME});
            res.setPropertyValues(new String[]{"yes"});
            
            commandId = null;
        } else {
            res.setPropertyNames(new String[]{});
            res.setPropertyValues(new String[]{});
        }
        
        return res;
    }
    
    public PEvent handleEvent(Displayable displayable, Item Item, Command command) {
        return new PEvent(getController().askToPersist(command),ProtocolConstants.EVENT_KIND_COMMAND);
    }
}
